/**
 * 预加载脚本 (Preload Script)
 * 
 * 这个文件在渲染进程中运行，但可以访问 Node.js API
 * 它充当主进程和渲染进程之间的安全桥梁
 * 
 * 主要职责：
 * 1. 通过 contextBridge 安全地向渲染进程暴露 Electron API
 * 2. 防止渲染进程直接访问 Node.js API，提高安全性
 * 3. 提供受控的系统功能访问接口
 */

// 导入 Electron 的上下文桥接模块
import { contextBridge } from 'electron'
// 导入 Electron 工具包提供的预构建 API
import { electronAPI } from '@electron-toolkit/preload'

/**
 * 自定义 API 对象
 * 可以在这里添加应用特定的功能接口
 * 这些 API 将通过 contextBridge 暴露给渲染进程
 */
const api = {
  // 系统信息获取
  system: {
    /**
     * 获取系统基本信息
     */
    getInfo: () => {
      const os = require('os')
      return {
        platform: os.platform(),
        arch: os.arch(),
        hostname: os.hostname(),
        uptime: os.uptime(),
        totalMemory: Math.round(os.totalmem() / 1024 / 1024 / 1024) + 'GB',
        freeMemory: Math.round(os.freemem() / 1024 / 1024 / 1024) + 'GB'
      }
    },

    /**
     * 获取CPU信息
     */
    getCpuInfo: () => {
      const os = require('os')
      const cpus = os.cpus()
      return {
        model: cpus[0]?.model || 'Unknown',
        cores: cpus.length,
        speed: cpus[0]?.speed || 0
      }
    },

    // 系统托盘功能
    createTray: async (options: any) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-create-tray', options)
    },

    destroyTray: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-destroy-tray')
    },

    updateTrayMenu: async (menu: any[]) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-update-tray-menu', menu)
    },

    getTrayStatus: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-get-tray-status')
    },

    // 全局快捷键
    registerGlobalShortcut: async (accelerator: string, action: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-register-shortcut', { accelerator, action })
    },

    unregisterGlobalShortcut: async (accelerator: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-unregister-shortcut', accelerator)
    },

    // 系统通知
    showNotification: async (options: any) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-show-notification', options)
    },

    // 应用菜单
    setApplicationMenu: async (template: any) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-set-app-menu', template)
    },

    setMenuBarVisibility: async (visible: boolean) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-set-menubar-visibility', visible)
    },

    // 协议注册
    registerProtocol: async (protocol: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-register-protocol', protocol)
    },

    // 开机自启动
    setAutoLaunch: async (enabled: boolean) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-set-auto-launch', enabled)
    },

    getAutoLaunchStatus: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('system-get-auto-launch-status')
    }
  },

  // 菜单事件监听
  onMenuAction: (callback: (action: any) => void) => {
    const { ipcRenderer } = require('electron')
    ipcRenderer.on('menu-action', (event, action) => {
      callback(action)
    })
  },

  // 硬件访问相关
  hardware: {
    // 屏幕截图相关
    captureScreen: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-capture-screen')
    },

    captureWindow: async (windowId?: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-capture-window', windowId)
    },

    captureSource: async (sourceId: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-capture-source', sourceId)
    },

    getScreenSources: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-screen-sources')
    },

    saveImage: async (dataUrl: string, fileName: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-save-image', dataUrl, fileName)
    },

    // 屏幕录制相关
    startScreenRecording: async (options?: { audio?: boolean; video?: boolean }) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-start-screen-recording', options)
    },

    // Windows专用屏幕录制
    startWindowsScreenRecording: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-start-windows-screen-recording')
    },

    // 测试屏幕源是否可捕获
    testSourceCapturable: async (sourceId: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-test-source-capturable', sourceId)
    },

    stopScreenRecording: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-stop-screen-recording')
    },

    // 摄像头相关
    getCameraDevices: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-camera-devices')
    },

    startCamera: async (deviceId?: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-start-camera', deviceId)
    },

    stopCamera: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-stop-camera')
    },

    // 麦克风相关
    getMicrophoneDevices: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-microphone-devices')
    },

    startMicrophone: async (deviceId?: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-start-microphone', deviceId)
    },

    stopMicrophone: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-stop-microphone')
    },

    saveAudio: async (audioBlob: Blob, fileName: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-save-audio', audioBlob, fileName)
    },

    // 系统信息相关
    getDisplayInfo: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-display-info')
    },

    getPowerInfo: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-power-info')
    },

    getSystemInfo: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-system-info')
    },

    getCPUInfo: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-cpu-info')
    },

    getMemoryInfo: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-get-memory-info')
    },

    preventSystemSleep: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-prevent-system-sleep')
    },

    allowSystemSleep: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('hardware-allow-system-sleep')
    }
  },

  // 文件操作
  file: {
    /**
     * 显示文件选择对话框
     */
    showOpenDialog: async (options: any = {}) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('show-open-dialog', options)
    },

    /**
     * 显示保存文件对话框
     */
    showSaveDialog: async (options: any = {}) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('show-save-dialog', options)
    },

    /**
     * 读取文件内容
     */
    readFile: async (filePath: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('read-file', filePath)
    },

    /**
     * 写入文件内容
     */
    writeFile: async (filePath: string, content: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('write-file', filePath, content)
    },

    /**
     * 获取文件信息
     */
    getFileInfo: async (filePath: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('get-file-info', filePath)
    },

    /**
     * 导入文件 - 选择并读取文件内容
     */
    importFile: async (options: any = {}) => {
      const { ipcRenderer } = require('electron')
      try {
        // 显示文件选择对话框
        const dialogResult = await ipcRenderer.invoke('show-open-dialog', {
          properties: ['openFile'],
          filters: [
            { name: '文本文件', extensions: ['txt', 'md'] },
            { name: 'JSON文件', extensions: ['json'] },
            { name: '所有文件', extensions: ['*'] }
          ],
          ...options
        })

        if (dialogResult.canceled || !dialogResult.filePaths.length) {
          return { success: false, canceled: true }
        }

        // 读取选中的文件
        const filePath = dialogResult.filePaths[0]
        const fileResult = await ipcRenderer.invoke('read-file', filePath)
        
        return {
          success: fileResult.success,
          filePath,
          ...fileResult
        }
      } catch (error) {
        return {
          success: false,
          error: error instanceof Error ? error.message : String(error)
        }
      }
    },

    /**
     * 导出文件 - 保存内容到文件
     */
    exportFile: async (content: string, options: any = {}) => {
      const { ipcRenderer } = require('electron')
      try {
        // 显示保存文件对话框
        const dialogResult = await ipcRenderer.invoke('show-save-dialog', {
          defaultPath: 'export.txt',
          filters: [
            { name: '文本文件', extensions: ['txt'] },
            { name: 'JSON文件', extensions: ['json'] },
            { name: '所有文件', extensions: ['*'] }
          ],
          ...options
        })

        if (dialogResult.canceled || !dialogResult.filePath) {
          return { success: false, canceled: true }
        }

        // 写入文件
        const writeResult = await ipcRenderer.invoke('write-file', dialogResult.filePath, content)
        
        return {
          success: writeResult.success,
          filePath: dialogResult.filePath,
          ...writeResult
        }
      } catch (error) {
        return {
          success: false,
          error: error instanceof Error ? error.message : String(error)
        }
      }
    }
  },

  // 应用控制
  app: {
    /**
     * 获取应用版本信息
     */
    getVersion: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('get-app-version')
    },

    /**
     * 获取应用完整信息
     */
    getInfo: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('get-app-info')
    },

    /**
     * 重启应用
     */
    restart: () => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('app-restart')
    },

    /**
     * 退出应用
     */
    quit: () => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('app-quit')
    }
  },

  // 窗口控制
  window: {
    /**
     * 最小化窗口
     */
    minimize: () => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('window-minimize')
    },

    /**
     * 最大化窗口
     */
    maximize: () => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('window-maximize')
    },

    /**
     * 最大化/还原窗口切换
     */
    toggleMaximize: () => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('window-toggle-maximize')
    },

    /**
     * 关闭窗口
     */
    close: () => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('window-close')
    },

    /**
     * 设置窗口置顶
     */
    setAlwaysOnTop: (flag: boolean) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('window-set-always-on-top', flag)
    },

    /**
     * 创建子窗口
     */
    createChild: async (options: any = {}) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('create-child-window', options)
    },

    /**
     * 获取窗口列表
     */
    getList: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('get-window-list')
    },

    /**
     * 关闭子窗口
     */
    closeChild: (windowId: string) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('close-child-window', windowId)
    },

    /**
     * 聚焦到指定窗口
     */
    focus: (windowId: number) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('focus-window', windowId)
    },

    /**
     * 监听子窗口关闭事件
     */
    onChildClosed: (callback: (data: { windowId: string }) => void) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.on('child-window-closed', (_, data) => callback(data))
    }
  },

  // 通知功能
  notification: {
    /**
     * 显示系统通知
     */
    show: (options: { title: string; body: string; icon?: string }) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('show-notification', options)
    }
  },

  // 主题控制
  theme: {
    /**
     * 获取系统主题
     */
    getSystemTheme: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('get-system-theme')
    },

    /**
     * 监听主题变化
     */
    onThemeChange: (callback: (theme: 'light' | 'dark') => void) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.on('theme-changed', (_, theme) => callback(theme))
    }
  },

  // 存储功能
  storage: {
    /**
     * 获取存储的值
     */
    get: async (key: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('storage-get', key)
    },

    /**
     * 设置存储的值
     */
    set: async (key: string, value: any) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('storage-set', key, value)
    },

    /**
     * 删除存储的值
     */
    delete: async (key: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('storage-delete', key)
    },

    /**
     * 清空所有存储
     */
    clear: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('storage-clear')
    },

    /**
     * 获取所有存储的键
     */
    keys: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('storage-keys')
    }
  },

  // 网络功能
  network: {
    /**
     * 检查网络连接状态
     */
    checkConnection: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('check-network')
    }
  },

  // 剪贴板功能
  clipboard: {
    /**
     * 读取剪贴板文本
     */
    readText: async () => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('clipboard-read-text')
    },

    /**
     * 写入文本到剪贴板
     */
    writeText: async (text: string) => {
      const { ipcRenderer } = require('electron')
      return await ipcRenderer.invoke('clipboard-write-text', text)
    }
  },

  // 消息广播（渲染进程间通信）
  broadcast: {
    /**
     * 向其他渲染进程广播消息
     */
    send: (channel: string, data: any, excludeSelf = true) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('broadcast-message', { channel, data, excludeSender: excludeSelf })
    },

    /**
     * 监听来自其他渲染进程的广播消息
     */
    on: (channel: string, callback: (data: any) => void) => {
      const { ipcRenderer } = require('electron')
      console.log(`[Preload] 设置广播监听器: ${channel}`)
      
      const wrappedCallback = (_, data) => {
        console.log(`[Preload] 收到广播消息 - 频道: ${channel}, 数据:`, data)
        callback(data)
      }
      
      ipcRenderer.on(channel, wrappedCallback)
    },

    /**
     * 移除监听器
     */
    off: (channel: string, callback?: (data: any) => void) => {
      const { ipcRenderer } = require('electron')
      if (callback) {
        ipcRenderer.removeListener(channel, callback)
      } else {
        ipcRenderer.removeAllListeners(channel)
      }
    }
  },

  // 自定义事件系统
  events: {
    /**
     * 发送自定义事件
     */
    emit: (eventName: string, data: any) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('emit-custom-event', { eventName, data })
    },

    /**
     * 监听自定义事件
     */
    on: (eventName: string, callback: (data: any) => void) => {
      const { ipcRenderer } = require('electron')
      ipcRenderer.send('listen-custom-event', eventName)
      ipcRenderer.on('custom-event-received', (_, { eventName: receivedEventName, data }) => {
        if (receivedEventName === eventName) {
          callback(data)
        }
      })
    }
  }
}

/**
 * 安全地向渲染进程暴露 API
 * 
 * 如果启用了上下文隔离（推荐的安全做法），使用 contextBridge
 * 否则直接添加到 DOM 全局对象上
 */
if (process.contextIsolated) {
  try {
    // 将 Electron API 暴露为 window.electron
    contextBridge.exposeInMainWorld('electron', electronAPI)
    // 将自定义 API 暴露为 window.api
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // 兼容模式：直接赋值给 window 对象
  // @ts-ignore (在 dts 文件中定义)
  window.electron = electronAPI
  // @ts-ignore (在 dts 文件中定义)
  window.api = api
}
